import {
  Row, Typography, Col, Tabs, Tag, Space, Skeleton, message
} from 'antd';
import { useParams } from 'react-router-dom';

import { useEffect, useState, useCallback } from 'react';
import { useRequest } from 'ahooks';
import TemplateDeatil from './components/template-detail/template';
import QRCode from
  './components/questionnaire-detail/components/qr-code';
import QuestionnaireOptions from './components/questionnaire-detail/options';
import QuestionHide from './components/questionnaire-detail/question-hide';
import QuestionnaireOpen from
  './components/questionnaire-detail/questionnaire-open';
import QuestionnaireInfoUpdate
  from
  './components/questionnaire-detail/questionnaire-info-update';
import * as APIS from '../../constants/api-constants';

const { Title } = Typography;
const { TabPane } = Tabs;

interface Props {
  templateUuid: string,
  questionnaireUuid: string
}

export default () => {
  const [isInitComplate, setIsInitComplate] = useState(false);
  const { templateUuid, questionnaireUuid }: Props = useParams();
  const [currentTemplate, setCurrentTemplate] = useState<
    Questionnaire.Template
  >();
  const [currentQuestionnaire, setCurrentQuestionnaire] = useState<
    Questionnaire.QuestionnaireItem
  >();

  /**
   * 获取uuid对应的template
   */
  const {
    run: runTemplate,
    loading: templateLoading
  } = useRequest((uuid) => ({
    url: APIS.TEMPLATE,
    method: 'GET',
    params: {
      uuid
    }
  }), {
    manual: true,
    onSuccess: (res) => {
      setCurrentTemplate(res.data.template);
    },
    onError: (err) => {
      console.log(err);
    },
  });

  useEffect(() => { runTemplate(templateUuid); }, [templateUuid]);
  /**
   * 获取uuid对应的questionnaire
   */
  const {
    run: runQuestionnaire,
    loading: questionnaireLoading
  } = useRequest((uuid) => ({
    url: APIS.QUESTIONNAIRE,
    method: 'GET',
    params: {
      uuid
    }
  }), {
    manual: true,
    onSuccess: (res) => {
      setCurrentQuestionnaire(res.data.questionnaire);
    },
    onError: (err) => {
      console.log(err);
    },
  });

  const handleQuestionnaireChange = useCallback(() => {
    runQuestionnaire(questionnaireUuid);
  }, [questionnaireUuid]);

  // 改变问卷开启状态
  const { run: changeOpenState, loading: changeLoading } = useRequest((
    currentOpen
  ) => ({
    url: APIS.QUESTIONNAIRE_SWITCH,
    method: 'PUT',
    data: {
      uuid: questionnaireUuid,
      open: currentOpen
    }
  }), {
    manual: true,
    onSuccess: (res) => {
      const { open: currentOpenState } = res.data;
      if (currentOpenState === 1) {
        handleQuestionnaireChange();
        message.success('问卷已开启');
      } else if (currentOpenState === 0) {
        handleQuestionnaireChange();
        message.success('问卷已关闭');
      }
    },
    onError: () => {
      message.error('设置失败, 请刷新页面再试');
    }
  });

  useEffect(() => {
    runQuestionnaire(questionnaireUuid);
  }, [questionnaireUuid]);

  useEffect(() => {
    if (
      !isInitComplate
      && currentTemplate
      && !templateLoading
      && currentQuestionnaire
      && !questionnaireLoading
    ) {
      setIsInitComplate(true);
    }
  }, [
    templateLoading,
    questionnaireLoading,
    currentTemplate,
    currentQuestionnaire,
    isInitComplate
  ]);

  return (
    <Skeleton
      active
      loading={!isInitComplate}
    >
      <Row>
        <Col>
          <Title level={2}>
            <Space>
              <span>
                {currentTemplate?.title}
                ——
                {currentQuestionnaire?.name}
              </span>
              {
                currentQuestionnaire?.open
                  ? <Tag color="#2db7f5">已开启</Tag>
                  : <Tag color="#f50">未开启</Tag>
              }
            </Space>
          </Title>
        </Col>
      </Row>
      <Row style={{ width: '100%' }} justify="space-between" gutter={16}>
        <Col span={18}>
          <TemplateDeatil currentTemplate={currentTemplate} />
        </Col>
        <Col span={6}>
          <QRCode qrcode={currentQuestionnaire?.QRCode} />
        </Col>
      </Row>
      <Tabs
        defaultActiveKey="1"
      >
        <TabPane tab="基本信息选项内容配置" key="1">
          <QuestionnaireOptions
            questionnaireUuid={questionnaireUuid}
            handleAlter={() => { runQuestionnaire(questionnaireUuid); }}
          />
        </TabPane>
        <TabPane tab="基本信息隐藏配置" key="2">
          <QuestionHide
            currentQuestionnaire={currentQuestionnaire}
            handleAlter={() => { runQuestionnaire(questionnaireUuid); }}
          />
        </TabPane>
        <TabPane tab="问卷开放配置" key="3">
          <QuestionnaireOpen
            changeOpenState={changeOpenState}
            changeLoading={changeLoading}
            initialOpen={Boolean(currentQuestionnaire?.open)}
          />
        </TabPane>
        <TabPane tab="二级问卷基本信息配置" key="4">
          <QuestionnaireInfoUpdate
            // FIXME: 这里需要传入一个可以刷新本页面的 isFresh
            handleAlter={() => { runQuestionnaire(questionnaireUuid); }}
            questionnaireUuid={questionnaireUuid}
          />
        </TabPane>
      </Tabs>
    </Skeleton>
  );
};
